<template>
    <div class="layout">
        <div class="title">
            <div class="title-label">
                <span class="title-label-text">关键指标分析</span>
                <el-tooltip effect="dark" placement="top-start">
                    <template #content>
                        <div>新增客户数：筛选条件下，新增企微客户数+非企微客户数，包含流失客户数。</div>
                        <div>新增企微客户数：筛选条件下，添加员工企微的客户数，去除流失客户数，不去重。</div>
                        <div>未分配客户数：筛选条件下，没有归属员工的客户总数。</div>
                        <div>流失客户数：筛选条件下，删除所有已添加企微员工的客户总数。</div>
                    </template>
                    <span class="title-label-text-icon">
                        <el-icon color="#ccc" size="16"><QuestionFilled /></el-icon>
                    </span>
                </el-tooltip>
            </div>
            <div class="title-right">
                <el-select
                    v-model="departItem.departList"
                    multiple
                    clearable
                    popper-class="zw-hide_select_option"
                    :collapse-tags="true"
                    placeholder="请选择成员/部门"
                    @removeTag="handleRemoveTag"
                    @click="handleSelectDepartClick"
                    @clear="handleSelectDepartClear">
                    <el-option
                        v-for="option in departItem.departList"
                        :key="option.id"
                        :label="option.name"
                        :value="option.id"
                        :disabled="option.disabled" />
                </el-select>
                <el-date-picker
                    v-model="form.screen_time"
                    style="margin: 0 8px; width: 292px"
                    type="daterange"
                    :teleported="false"
                    :editable="false"
                    :default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    range-separator="—"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :disabled-date="disabledDate"
                    @change="handleTimeChange"
                    @calendar-change="calendarChange" />
                <el-button plain @click="summaryExport">导出</el-button>
            </div>
        </div>
        <!-- 暂时隐藏 -->
        <!-- <div class="tab-list">
            <div
                v-for="(item, index) in tabList"
                :key="index"
                class="tab-item"
                :class="{ 'tab-item-active': item.active }"
                @click="onTabItem(index)">
                <div class="tab-item-name">{{ item.name }}</div>
                <div class="tab-item-num">{{ item.number }}</div>
            </div>
        </div> -->
        <div class="tab-list-two">
            <div class="tab-list-two-content">
                <div
                    v-for="(item, index) in tabList"
                    :key="index"
                    class="tab-item"
                    :class="{ 'tab-item-active': item.active }"
                    @click="onTabItem(index)">
                    <div class="tab-item-name">{{ item.name }}</div>
                </div>
            </div>
        </div>
        <div class="chart_box">
            <div v-if="isShoweCharts" ref="myRef" class="chart_line"></div>
        </div>
        <el-empty v-if="!isShoweCharts" description="暂无数据"></el-empty>
    </div>
    <!-- 部门人员弹框 -->
    <ZWDepart ref="ZWDepartRef" v-model:show="show" v-bind="departItem" @submit="onDepartSubmit" />
</template>

<script setup lang="ts">
import { ref, inject, reactive, watch, nextTick, onMounted } from 'vue';
import { cusLineInfo, summarySyncExport } from '@/api/customerCenter';
import { getDay } from '@/utils/utils';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';

import ZWDepart from '@/components/zw/depart/Depart';

const echarts: any = inject('ec');

const emit = defineEmits(['lastUpdateTime']);

const isShoweCharts = ref(false);
const xData = ref([]);
const yData = ref([]);
const myRef = ref(null);

const ZWDepartRef = ref(null);

const pickDay = ref();
const show = ref(false);
const departList = ref([]);

const departItem: any = reactive({
    label: '选择成员和部门',
    type: 'depart',
    userKey: 'depart',
    popperClass: 'zw-hide_select_option',
    departmentKey: 'departments',
    placeholder: '全部',
    multiple: true,
    isMember: false,
    departList: [],
    selectedMember: []
});

const form = reactive({
    screen_time: [getDay(-7), getDay(-1, true)],
    source: 1,
    departments: [],
    users: []
});

const tabList = reactive<any>([
    { name: '新增客户数', source: 1, number: 0, active: true, code: 'add_cust_num' },
    { name: '新增企微客户数', source: 2, number: 0, active: false, code: 'add_qw_cust_num' },
    { name: '未分配客户数', source: 3, number: 0, active: false, code: 'undistributed_cust_num' },
    { name: '流失客户数', source: 5, number: 0, active: false, code: 'lost_cust_num' }
]);

/**
 * tab类型切换事件
 */
const onTabItem = (index: number) => {
    if (tabList[index].active) return;
    tabList.map((el: any) => (el.active = false));
    tabList[index].active = true;
    form.source = tabList[index].source;
    getLineInfo();
};

/**
 * 点击成员/部门选项展开
 */
const handleSelectDepartClick = (item: any) => {
    show.value = true;
    departItem.selectedMember = departItem.departList?.filter(el => el.id);
};

const handleSelectDepartClear = () => {
    form.users = [];
    form.departments = [];
    ZWDepartRef.value.removeAll();
    getLineInfo();
};

const handleRemoveTag = () => {
    form.users = departItem.departList.filter((el: any) => el.type == 'user').map((el: any) => el.id);
    form.departments = departItem.departList.filter((el: any) => el.type == 'department').map((el: any) => el.id);
    getLineInfo();
};

const onDepartSubmit = (data: any) => {
    departItem.departList = [...data];
    form.users = data.filter((el: any) => el.type == 'user').map((el: any) => el.id);

    form.departments = data.filter((el: any) => el.type == 'department').map((el: any) => el.id);

    getLineInfo();
};

const disabledDate = (time: any) => {
    if (!pickDay.value) {
        return time.getTime() > Date.now() - 3600 * 1000 * 24;
    }
    const con1 = new Date(pickDay.value).getTime() - 364 * 24 * 60 * 60 * 1000;
    const con2 = new Date(pickDay.value).getTime() + 364 * 24 * 60 * 60 * 1000;
    const con3 = time.getTime() > Date.now() - 3600 * 1000 * 24;
    return con3 ? con3 : time.getTime() < con1 || time.getTime() > con2;
};

/**
 * 时间变动
 */
const handleTimeChange = (val: any) => {
    if (!val) {
        pickDay.value = '';
        return;
    }
    getLineInfo();
};

const calendarChange = (val: Date[]) => {
    const [pointDay] = val;
    pickDay.value = pointDay;
};

const onTooltip = (status: number) => {
    switch (status) {
        case 1:
            return '新增客户数';
        case 2:
            return '新增企微客户数';
        case 3:
            return '未分配客户数';
        case 5:
            return '流失客户数';
    }
};

const summaryExport = async e => {
    const res = await summarySyncExport(form);
    parabolaAnimation(e);
    res && ShowTaskMessage('关键指标分析数据导出异步任务创建成功');
};

// 获取折线图数据
const getLineInfo = async () => {
    xData.value = [];
    yData.value = [];
    const res: any = await cusLineInfo(form);
    const list: any = res.data || [];
    const summary: any = res.summary || {};
    tabList.map((el: any) => {
        if (el.code == 'add_cust_num') {
            el.number = summary.add_cust_num || 0;
        }
        if (el.code == 'add_qw_cust_num') {
            el.number = summary.add_qw_cust_num || 0;
        }
        if (el.code == 'undistributed_cust_num') {
            el.number = summary.undistributed_cust_num || 0;
        }
        if (el.code == 'lost_cust_num') {
            el.number = summary.lost_cust_num || 0;
        }
    });
    if (list.length) {
        isShoweCharts.value = true;
        nextTick(() => {
            list.map((item: any) => {
                xData.value.push(item.date);
                yData.value.push(item.num);
            });
        });
    } else {
        isShoweCharts.value = false;
    }
    emit('lastUpdateTime', res.last_update_time);
};

/**
 * 折线图echarts渲染
 */
const getEchart = () => {
    const myChart = echarts.init(myRef.value);
    myChart.setOption({
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    show: false
                }
            }
        },
        grid: {
            top: 22,
            bottom: 28,
            left: 36,
            right: 60,
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: xData.value
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: onTooltip(form.source),
                data: yData.value,
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 0,
                areaStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#F8DCD1' },
                            { offset: 0.5, color: '#FDF8F6' },
                            { offset: 1, color: '#FFFAF9' }
                        ])
                    }
                },
                itemStyle: {
                    normal: {
                        borderWidth: 2,
                        color: '#FF6B00'
                    }
                },
                emphasis: {
                    // 鼠标 hover 时的样式
                    itemStyle: {
                        color: '#FF9D23', // hover 圆点颜色
                        borderColor: '#FF9D23', // hover 圆点边框颜色
                        borderWidth: 8
                    }
                }
            }
        ]
    });
    nextTick(() => {
        myChart.resize();
    });
    window.onresize = function () {
        myChart.resize();
    };
};
/**
 * @description: 监听x轴数据变化，有数据时渲染echarts
 * @return {*}
 */
watch(
    () => xData.value,
    val => {
        if (val.length) {
            nextTick(() => {
                getEchart();
            });
        }
    },
    { deep: true }
);

onMounted(getLineInfo);
</script>

<style lang="scss" scoped>
.layout {
    margin-top: 16px;

    // min-width: 1498px;
    box-sizing: border-box;
    background-color: #ffff;
    border: 1px solid #e4e7ed;
    border-radius: 4px;

    .title {
        padding: 17px 24px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #eaeaea;

        .title-label {
            display: flex;
            align-items: center;
            font-size: 16px;
            font-family: PingFangSC-Medium, 'PingFang SC';
            font-weight: 500;
            color: #33302d;
            line-height: 22px;

            .title-label-text-icon {
                display: inline-flex;
                margin-left: 8px;
                align-items: center;
                cursor: pointer;

                .el-icon {
                    margin-right: 2px;
                }
            }
        }

        .title-right {
            display: flex;
            align-items: center;

            .title-times {
                margin: 0 8px;
            }
        }
    }

    .tab-list {
        margin: 24px 0 24px 24px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .tab-item {
            flex: 1;
            margin-right: 24px;
            padding: 16px 24px;

            // height: 90px;
            background: #f9f9f9;
            border-radius: 4px;
            cursor: pointer;

            .tab-item-name {
                font-size: 14px;
                font-family: PingFangSC-Regular, 'PingFang SC';
                font-weight: 400;
                color: #666;
                line-height: 20px;
            }

            .tab-item-num {
                padding-top: 8px;
                height: 30px;
                font-size: 30px;
                font-family: HelveticaNeue-Medium, HelveticaNeue;
                font-weight: 500;
                color: #33302d;
                line-height: 30px;
            }
        }

        .tab-item-active {
            background: #fdefe5;
            border: 1px solid #ff6b00;
            border-radius: 4px;

            .tab-item-name {
                color: #ff6b00;
            }

            .tab-item-num {
                color: #ff6b00;
            }
        }
    }

    .tab-list-two {
        margin: 24px 0 24px 24px;
        display: flex;

        .tab-list-two-content {
            display: flex;
            align-items: center;
            border: 1px solid #e4e7ed;
            border-radius: 4px;
            overflow: hidden;
        }

        .tab-item {
            padding: 8px 15px;
            border-right: 1px solid #e4e7ed;
            cursor: pointer;

            .tab-item-name {
                font-size: 14px;
                font-family: PingFangSC-Regular, 'PingFang SC';
                font-weight: 400;
                color: #666;
                line-height: 20px;
            }
        }

        .tab-item:nth-last-child(1) {
            border-right: none;
        }

        .tab-item-active {
            background: #ff6b00;

            .tab-item-name {
                color: #fff;
            }
        }
    }

    .head-btn {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .chart_line {
        width: 100%;
        height: 400px;
    }
}
</style>
